`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2020/09/22 21:18:26
// Design Name: 
// Module Name: LCDControl
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////

// wr = rw, 1: read, 0: write
// rd = e
// rs = a0, 1: data, 0: inst


`define RST_0 1
`define RST_1 2
`define RESET 3

`define TRANS_0 4
`define TRANS_1 5
`define TRANS_2 6


module LCDControl(
    input   wire        rst,
    input   wire        clk,
    
    input   wire [31:0] i_data,
    input   wire        i_en,
    
    output  wire        o_cs,
    output  wire        o_wr,
    output  wire        o_rd,
    output  wire        o_rs,
    output  wire [7:0]  o_data,
    output  wire        o_rst
    );
    
    
    reg cs = 1;
    reg wr = 0;
    reg rd = 0;
    reg rs = 0;
    reg [7:0] data = 0;
    reg r = 1;
    
    assign o_cs = cs;
    assign o_wr = wr;
    assign o_rd = rd;
    assign o_rs = rs;
    assign o_data = data;
    assign o_rst = r;
    
    
    reg in_delay = 0;
    reg [31:0] delay_cycles;
    reg [31:0] state = 0;
    
    always @(posedge clk) begin
        if (rst == 0) begin
            r <= 0;
            in_delay <= 1;
            delay_cycles <= 5;
            state <= `RST_1;
        end else begin
            if (in_delay) begin
                delay_cycles <= delay_cycles - 1;
                if (delay_cycles == 0) begin
                    in_delay <= 0;
                end
            end else begin
                if (state == `RST_1) begin
                    in_delay <= 1;
                    delay_cycles <= 1;
                    r <= 1;
                    state <= `RESET;
                end else if (state == `RESET) begin
                    if (i_en) begin
                        cs <= 0;
                        rs <= i_data[8];
                        rd <= 0;
                        in_delay <= 1;
                        delay_cycles <= 100;
                        state <= `TRANS_1;
                    end
                end else if (state == `TRANS_1) begin
                    wr <= 0;
                    data <= i_data[7:0];
                    rd <= 1;
                    in_delay <= 1;
                    delay_cycles <= 100;
                    state <= `TRANS_2;
                end else if (state == `TRANS_2) begin
                    cs <= 1;
                    rd <= 0;
                    state <= `RESET;
                end
            end
        end
    end
endmodule
